package com.zzedu.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.zzedu.common.annotation.Log;
import com.zzedu.common.core.controller.BaseController;
import com.zzedu.common.core.domain.AjaxResult;
import com.zzedu.common.core.page.TableDataInfo;
import com.zzedu.common.enums.BusinessType;
import com.zzedu.common.utils.ServletUtils;
import com.zzedu.common.utils.StringUtils;
import com.zzedu.common.utils.poi.ExcelUtil;
import com.zzedu.domain.ZzSchool;
import com.zzedu.domain.ZzSchoolCourseR;
import com.zzedu.dto.ZzSchoolDTO;
import com.zzedu.framework.transaction.ITransactionHandlerService;
import com.zzedu.params.OperateSchoolCourseRelatedParams;
import com.zzedu.service.IZzSchoolCourseRService;
import com.zzedu.service.IZzSchoolService;
import com.zzedu.vo.ZzSchoolReportVO;
import com.zzedu.vo.ZzSchoolVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 学校管理Controller
 *
 * @author Mr.Wang
 * @date 2025-01-27
 */
@RestController
@RequestMapping("/school/schoolinfo")
public class ZzSchoolController extends BaseController {
    @Autowired
    private IZzSchoolService zzSchoolService;

    @Autowired
    private IZzSchoolCourseRService zzSchoolCourseRService;

    @Autowired
    private ITransactionHandlerService transactionHandlerService;
    /**
     * 查询学校管理列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:schoolinfo:query')")
    @RequestMapping("/list")
    public TableDataInfo list(@RequestBody ZzSchoolDTO zzSchool) {
        IPage<ZzSchool> page = zzSchoolService.page(zzSchool.getPageDTO(), zzSchoolService.buildQuery(zzSchool));
        return getDataTable(page, zzSchoolService.convertVO(page.getRecords()));
    }

    /**
     * 导出学校管理列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:schoolinfo:export')")
    @Log(title = "学校管理", businessType = BusinessType.EXPORT)
    @RequestMapping("/export")
    public void export(ZzSchoolDTO zzSchool) {
        List<ZzSchool> list = zzSchoolService.list(zzSchoolService.buildQuery(zzSchool));
        ExcelUtil<ZzSchoolVO> util = new ExcelUtil<ZzSchoolVO>(ZzSchoolVO.class);
        util.exportExcel(ServletUtils.getResponse(), zzSchoolService.convertVO(list), "学校管理数据");
    }


    /**
     * 新增保存学校管理
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:schoolinfo:add')")
    @Log(title = "学校管理", businessType = BusinessType.INSERT)
    @RequestMapping("/add")
    public AjaxResult addSave(@RequestBody ZzSchoolDTO zzSchoolDTO) {
        zzSchoolDTO.setTel(StringUtils.trimToEmpty(zzSchoolDTO.getTel()));
        return toAjax(zzSchoolService.save(zzSchoolDTO));
    }


    /**
     * 获取学校管理详细信息
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:schoolinfo:query')")
    @RequestMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        ZzSchoolVO zzSchoolVO = zzSchoolService.convertVO(Lists.newArrayList(zzSchoolService.getById(id))).get(0);
        JSONObject jsonObject = (JSONObject) JSON.toJSON(zzSchoolVO);
        jsonObject.put("provinceAndCityAndDistrict", Lists.newArrayList(zzSchoolVO.getProvince(), zzSchoolVO.getCity(), zzSchoolVO.getDistrict()));
        return success(jsonObject);
    }


    /**
     * 修改保存学校管理
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:schoolinfo:edit')")
    @Log(title = "学校管理", businessType = BusinessType.UPDATE)
    @RequestMapping("/edit")
    public AjaxResult editSave(@RequestBody ZzSchoolDTO zzSchoolDTO) {
        return toAjax(zzSchoolService.updateById(zzSchoolDTO));
    }

    /**
     * 删除学校管理
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:schoolinfo:remove')")
    @Log(title = "学校管理", businessType = BusinessType.DELETE)
    @RequestMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(zzSchoolService.removeBatchByIds(ids));
    }


    /**
     * 增加、删除学校课程
     *
     * @return
     */
    @PreAuthorize("@permission.hasAnyPermissions('school:schoolinfo:edit')")
    @Log(title = "增加、删除学校课程", businessType = BusinessType.UPDATE)
    @RequestMapping("/manCourse")
    public AjaxResult manCourse(@Validated @RequestBody OperateSchoolCourseRelatedParams operateSchoolCourseRelatedParams) {
        return success(transactionHandlerService.runInTransaction(() -> {
            /**
             * 1-关联
             * 2-移除
             */
            if (2 == operateSchoolCourseRelatedParams.getOp()) {
                zzSchoolCourseRService.remove(Wrappers.lambdaQuery(ZzSchoolCourseR.class).eq(ZzSchoolCourseR::getSchoolId, operateSchoolCourseRelatedParams.getId())
                        .in(ZzSchoolCourseR::getCourseId, operateSchoolCourseRelatedParams.getCourseIdList())
                );
            } else if (1 == operateSchoolCourseRelatedParams.getOp()) {
                zzSchoolCourseRService.remove(Wrappers.lambdaQuery(ZzSchoolCourseR.class).eq(ZzSchoolCourseR::getSchoolId, operateSchoolCourseRelatedParams.getId())
                        .in(ZzSchoolCourseR::getCourseId, operateSchoolCourseRelatedParams.getCourseIdList())
                );
                List<ZzSchoolCourseR> zzSchoolCourseRS = operateSchoolCourseRelatedParams.getCourseIdList().stream().map(courseId -> {
                    ZzSchoolCourseR zzStuClassesR = new ZzSchoolCourseR();
                    zzStuClassesR.setCourseId(courseId);
                    zzStuClassesR.setSchoolId(operateSchoolCourseRelatedParams.getId());
                    return zzStuClassesR;
                }).collect(Collectors.toList());
                zzSchoolCourseRService.saveBatch(zzSchoolCourseRS);

            }
            return true;
        }));
    }



    /**
     * 学校报表数据
     */
    @PreAuthorize("@permission.hasAnyPermissions('zzedu:report:school')")
    @RequestMapping("/schoolReport")
    public TableDataInfo schoolReport(@RequestBody ZzSchoolDTO zzSchool) {
        IPage<ZzSchool> page = zzSchoolService.page(zzSchool.getPageDTO(), zzSchoolService.buildQuery(zzSchool));
        return getDataTable(page, zzSchoolService.convertSchoolVO(page.getRecords()));
    }

    /**
     * 导出学校管理列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('zzedu:report:school')")
    @Log(title = "学校管理", businessType = BusinessType.EXPORT)
    @RequestMapping("/exportReport")
    public void exportReport(ZzSchoolDTO zzSchool) {
        List<ZzSchool> list = zzSchoolService.list(zzSchoolService.buildQuery(zzSchool));
        ExcelUtil<ZzSchoolReportVO> util = new ExcelUtil<ZzSchoolReportVO>(ZzSchoolReportVO.class);
        util.exportExcel(ServletUtils.getResponse(), zzSchoolService.convertSchoolVO(list), "校区汇总数据");
    }
}
